package com.gaojinqi.controller;

import com.gaojinqi.config.WechatAccountConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 手动获取微信openID
 *
 * @author gaojinqi
 * @date 2019/5/5 22:00
 */
@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {

    public static final String ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    private final WechatAccountConfig wechatAccountConfig;

    @Autowired
    public WeixinController(WechatAccountConfig wechatAccountConfig) {
        this.wechatAccountConfig = wechatAccountConfig;
    }

    /**
     * 获取code
     *
     * @param code code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期
     * @return
     */
    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code) {
        log.info("进入auth方法。。。");
        log.info("code={}", code);
        // 获取poenID
        String url = ACCESS_TOKEN
                .replace("APPID", wechatAccountConfig.getMpAppId())
                .replace("SECRET", wechatAccountConfig.getMpAppSecret())
                .replace("CODE", code);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        log.info("response={}", response);
    }

    /**
     * 验证消息的确来自微信服务器
     *
     * @param echostr   随机字符串
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return 验证成功后一定要返回echostr给微信
     */
    @GetMapping("/portal")
    public String portal(@RequestParam("echostr") String echostr,
                         @RequestParam("signature") String signature,
                         @RequestParam("timestamp") String timestamp,
                         @RequestParam("nonce") String nonce
    ) {
        log.info("echostr=" + echostr +
                " nonce=" + nonce +
                " timestamp=" + timestamp +
                " signature=" + signature
        );
        // todo 1）将token、timestamp、nonce三个参数进行字典序排序 2）将三个参数字符串拼接成一个字符串进行sha1加密 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return echostr;
    }
}
